#!/usr/bin/env python
# -*- coding:utf-8 -*-
# fileName: login.py
import sys
from util.sendHttpReq import SendHttpReq
from util.getlog import get_log
from util.getAPIInfo import GetAPIInfo
from util import writeYaml
from configs import globalVariables
import json
import requests
import os
'''
功能：登录
入参：无
返回值：登录结果 response body
'''

class Login(object):
    def longin(self):
        apiInfo = GetAPIInfo().getAPISendInfo('login','api_login.yml')
        url = apiInfo['url']
        headers = apiInfo['headers']
        data =apiInfo['data']

        if isinstance(data,dict):
            data = json.dumps(data, sort_keys=True, indent = 4)
        # 忽略不安全的请求警告信息
        requests.packages.urllib3.disable_warnings()
        try:
            # 遇到requests的ssl验证，若想直接跳过不验证，设置verify=False即可
            response = requests.post(url=url, headers=headers, data=data, verify=False)
        except Exception as e:
            globalVariables.logger.error("发送login请求出错~ %s" % e)
        responseBody = response.json()

        #-------------将login response中返回的iamToken写入access_token.yml
        curPath = os.path.abspath(os.path.dirname(__file__))
        yamlPath = os.path.abspath(os.path.dirname(curPath) + os.path.sep + "configs/access_token.yml")

        tokenValue = {
            'access_token': responseBody["data"]["iamToken"]
        }
        writeYaml.writeYaml(tokenValue,yamlPath)
        globalVariables.logger.info('access token is: %s' % tokenValue)

        return responseBody

if __name__ == "__main__":
    login_api = Login()
    res= login_api.longin()
    print(res)

